import json
import requests

from flask import Flask, request, jsonify

app = Flask(__name__)

dialog_history = []


@app.route('/api/user_question', methods=['POST'])
def user_question():
    user_input = request.json['user_input']

    # 对用户问题进行编码
    user_input = {'role': 'user', 'content': user_input}

    # 构建prompt
    prompt = dialog_history + [user_input]

    # 调用ChatGLM-Pro生成回答
    response = requests.post('https://api.demo.com/chatgpt/generate', json={
        'prompt': prompt,
        'temperature': 0.5
    })

    # 处理响应
    if response.status_code != 200:
        return jsonify({'error': 'Error generating response'})

    generated = response.json()['generated_text']

    # 添加响应到对话历史
    dialog_history.append({'role': 'assistant', 'content': generated})

    return jsonify({'response': generated})


if __name__ == '__main__':
    app.run()